package com.xinzhi.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinzhi.domain.Product;
import com.xinzhi.domain.ProductType;
import com.xinzhi.domain.dto.ChangeProductTypeDto;
import com.xinzhi.domain.dto.ProductTypeDto;
import com.xinzhi.domain.vo.*;
import com.xinzhi.mapper.ProductMapper;
import com.xinzhi.mapper.ProductTypeMapper;
import com.xinzhi.service.ProductTypeService;
import com.xinzhi.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductTypeServiceImpl implements ProductTypeService {

    @Resource
    ProductTypeMapper productTypeMapper;

    @Resource
    ProductMapper productMapper;

    @Override
    public Result getProductOneType() {
        return Result.ok(productTypeMapper.getAllOneType());
    }

    @Override
    public Result getTwoTypeAndProduct(String id,String current) {
        // 需要给前端返回一级类目id 对应的二级分类  所有一级分类 以及 属于该一级类目的商品（分页）
        //==================================================================================
        // 参数校验 转换参数类型
        if (id == null || id == ""){
            return Result.error(10001,"参数为空");
        }
        Integer tempId = Integer.valueOf(id);

        // 当前页
        Integer tempCurrent;
        if (current == null || current == ""){
            tempCurrent = 1;
        }else {
            tempCurrent = Integer.valueOf(current);
        }
        if (tempCurrent < 1){
            tempCurrent = 1;
        }
        //===================================================================================
        // 查询所有一级分类
        QueryWrapper wrapper = new QueryWrapper();
        // 使用 Map 集合映射条件
        Map<String,Integer> oneTypeMap = new HashMap<>();
        oneTypeMap.put("father_type_id",0);
        oneTypeMap.put("delete_status",0);
        wrapper.allEq(oneTypeMap);
        List<ProductType> productTypeOneList = productTypeMapper.selectList(wrapper);
        //===================================================================================
        // 查询一级分类对应的二级分类
        QueryWrapper twoTypeWrapper = new QueryWrapper();
        // 使用 Map 集合映射条件
        Map<String,Integer> twoTypeMap = new HashMap<>();
        twoTypeMap.put("father_type_id",tempId);
        twoTypeMap.put("delete_status",0);
        twoTypeWrapper.allEq(twoTypeMap);
        List<ProductType> productTypeTwoList = productTypeMapper.selectList(twoTypeWrapper);
        //===================================================================================
        // 查询当前页商品
        QueryWrapper productWrapper = new QueryWrapper();
        // 使用 Map 集合映射条件
        Map<String,Integer> productConditionMap = new HashMap<>();
        productConditionMap.put("col_one_id",tempId);
        productConditionMap.put("delete_status",0);
        productConditionMap.put("putaway_status",1);
        productWrapper.allEq(productConditionMap);
        // 分页
        Page<Product> productPage = new Page<>(tempCurrent,8);
        Page page = productMapper.selectPage(productPage, productWrapper);
        // 获取当前页信息
        List<Product> productList = page.getRecords();
        // 取出商品简介
        List<ProductIntroVo> productIntroVoList = new ArrayList<>();
        for (Product product : productList) {
            ProductIntroVo productIntroVo = new ProductIntroVo();
            productIntroVo.setId(product.getId());
            productIntroVo.setProductName(product.getProductName());
            productIntroVo.setMainImg(product.getMainImg());
            productIntroVo.setPrice(product.getPrice());
            productIntroVo.setSalesVolume(product.getSalesVolume());
            productIntroVoList.add(productIntroVo);
        }
        //======================================================================
        // 返回信息
        OneTypeAndProductVo oneTypeAndProductVo = new OneTypeAndProductVo();
        oneTypeAndProductVo.setProductTypeListOne(productTypeOneList);
        oneTypeAndProductVo.setProductTypeListTwo(productTypeTwoList);
        oneTypeAndProductVo.setCurrent(page.getCurrent());
        oneTypeAndProductVo.setPages(page.getPages());
        oneTypeAndProductVo.setTotal(page.getTotal());
        oneTypeAndProductVo.setSize(page.getSize());
        oneTypeAndProductVo.setProductIntroVoList(productIntroVoList);
        return Result.ok(oneTypeAndProductVo);

    }

    @Override
    public Result queryProductType() {
        // 获取所有的一级分类
        List<ProductType> allOneType = productTypeMapper.getAllOneType();
        // 创建 返回Vo
        List<ProductTypeVo> productTypeVoList = new ArrayList<>();
        // 遍历一级分类赋值
        for (ProductType productType : allOneType) {
            ProductTypeVo productTypeVo = new ProductTypeVo();
            productTypeVo.setId(productType.getId());
            productTypeVo.setProductTypeName(productType.getProductTypeName());
            productTypeVo.setImg(productType.getImg());
            productTypeVo.setProductTypeTwoList(productTypeMapper.getTypeByOneTypeId(productType.getId()));
            // 追加到 productTypeVoList
            productTypeVoList.add(productTypeVo);
        }
        return Result.ok(productTypeVoList);
    }

    /**
     * 添加商品分类
     * @param productTypeDto
     * @return
     */
    @Override
    public Result addProductType(ProductTypeDto productTypeDto) {
        ProductType productType = new ProductType();

        productType.setProductTypeName(productTypeDto.getProductTypeName());
        productType.setImg(productTypeDto.getImg());
        // 如果 fatherTypeId 参数为空 说明此次请求添加的时一级分类 设置 fatherTypeId 属性值为空
        if (productTypeDto.getFatherTypeId() ==null){
            productType.setFatherTypeId(0);
        }else {
            productType.setFatherTypeId(productTypeDto.getFatherTypeId());
        }
        // 存入数据库
        Integer integer = productTypeMapper.addProductType(productType);
        if (integer == 0){
            return Result.error(50001,"系统异常");
        }
        return Result.ok("类目添加成功");
    }

    @Override
    public Result queryProductTypeDetail(String productTypeId) {
        // 参数校验
        if(productTypeId == "" || productTypeId == null){
            return Result.error(5000,"参数校验失败");
        }
        // 转换参数类型
        Integer tempProductTypeId = Integer.valueOf(productTypeId);
        // 创建返回对象
        ProductTypeDetailVo productTypeDetailVo = new ProductTypeDetailVo();
        // 查询类目信息
        ProductType productType = productTypeMapper.queryProductTypeById(tempProductTypeId);
        // 判断父类id是否存在
        String fatherTypeName = null;
        if(productType.getFatherTypeId() != null){
            fatherTypeName = productTypeMapper.queryProductTypeName(productType.getFatherTypeId());
        }

        // 返回对象赋值
        productTypeDetailVo.setId(productType.getId());
        productTypeDetailVo.setImg(productType.getImg());
        productTypeDetailVo.setProductTypeName(productType.getProductTypeName());
        productTypeDetailVo.setFatherTypeName(fatherTypeName);
        return Result.ok(productTypeDetailVo);


    }

    @Override
    public Result deleteProductType(String productTypeId) {
        // 参数校验
        if(productTypeId == "" || productTypeId == null){
            return Result.error(5000,"参数校验失败");
        }
        // 转换参数类型
        Integer tempProductTypeId = Integer.valueOf(productTypeId);
        // 查询类目对象
        ProductType productType = productTypeMapper.queryProductTypeById(tempProductTypeId);
        // 判断是否可以删除
        if (!(verdictProductType(productType))){
            return Result.error(50001,"删除失败，类目下还有商品/二级类目");
        }
        ProductType changeProductType = new ProductType();
        changeProductType.setId(tempProductTypeId);
        changeProductType.setDeleteStatus(1);
        // 修改类目删除状态
        Integer integer = productTypeMapper.updateProductType(changeProductType);
        if (integer == 0){
            return Result.error(50001,"系统异常");
        }
        return Result.ok("该类目已成功删除");
    }

    @Override
    public Result updateProductType(ChangeProductTypeDto changeProductTypeDto) {
        // 修改商品类目
        // 参数校验
        if (!(verifyParameter(changeProductTypeDto))){
            return Result.error(50001,"参数校验失败.请检查参数类型");
        }
        // 校验通过
        // 将DTO 参数赋值给 实体类
        ProductType productType = new ProductType();
        productType.setId(changeProductTypeDto.getId());
        productType.setProductTypeName(changeProductTypeDto.getProductTypeName());
        productType.setFatherTypeId(changeProductTypeDto.getFatherTypeId());
        productType.setImg(changeProductTypeDto.getImg());
        // 修改
        productTypeMapper.updateProductType(productType);
        return Result.ok("已成功修改");
    }

    /**
     *  校验修改商品类目参数
     * @param changeProductTypeDto
     * @return
     */
    public Boolean verifyParameter(ChangeProductTypeDto changeProductTypeDto){

        if (ObjectUtil.isEmpty(changeProductTypeDto)){
            return false;
        }
        if (changeProductTypeDto.getId() == null || changeProductTypeDto.getId() == 0){
            return false;
        }
        if (changeProductTypeDto.getProductTypeName() == null || changeProductTypeDto.getProductTypeName() == ""){
            return false;
        }
        return true;
    }



    /**
     * 判断该类目是否可以删除
     * @param productType
     * @return
     */
    public Boolean verdictProductType(ProductType productType){
        // 判断类目级别
        if (productType.getFatherTypeId() == 0){
            // 该类目属于一级类目  判断是否有对应的二级类目
            List<ProductType> typeByOneTypeId = productTypeMapper.getTypeByOneTypeId(productType.getId());
            if (typeByOneTypeId.size() != 0){
                return false;
            }
        }
        // 通过以上说明类目属于二级类目   判断该类目下是否有商品
        List<Product> productList = productMapper.queryProductByOneTypeOrTwoType(productType.getId());
        if (productList.size() != 0){
            return false;
        }
        return true;
    }
}
